(function ($) {
    $.fn.musicPlayer = function (playlist, options) {
        // Link external stylesheets:
        $("head").append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-darkness/jquery-ui.css" type="text/css" rel="stylesheet" />');
        $("head").append("<link href='http://fonts.googleapis.com/css?family=Raleway:100' rel='stylesheet' type='text/css'/>");

        // Global variables:
        var currentSong = 0;
        var repeatOne = false;

        var thePlayer = document.createElement("div");
        $(thePlayer).attr("id", "music-player-main");
        $(thePlayer).appendTo(this);

        // In case the playlist is empty:
        if (playlist === undefined) {
            $(".musicPlayer-currentSongTicker").html("Error loading music player: No playlist defined");
            $(".musicPlayer-currentSongTicker").addClass("ui-state-error");
        }

        // Controls hover settings:
        $(function () {
            $(".musicPlayer-icons")
                        .mouseenter(function () {
                            $(this).addClass('ui-state-hover');
                        })
                        .mouseleave(function () {
                            $(this).removeClass("ui-state-hover");
                        });
        });

        // Set options:
        var defaultOptions = {
            autoPlay: false,
            preload: "none",
            errorMsg: "Unskyld men sangen kan ikke blive loaded",
            showplaylist: false
        };

        var realOptions = $.extend(defaultOptions, options);
        var playlistShow = realOptions.showplaylist;


        return this.each(function () {
            /*********************************************************************************************************************************************************************/
            // HTML5 Audio and mp3 support:
            if (Modernizr.audio == true && Modernizr.audio.mp3) {
                // Create audio tag:
                var audioElem = document.createElement("audio");
                $(audioElem).attr("id", "audioPlayer");

                // Set first song source:
                if(playlist.length > 0)
                {
                    $(audioElem).attr("src", playlist[0][0]);

                    // Set current song information:
                    var currentSongElem = document.createElement("marquee");
                    $(currentSongElem).addClass("musicPlayer-currentSongTicker");
                    $(currentSongElem).html(playlist[0][1]);
                }
                $(currentSongElem).appendTo(thePlayer);

                // Set audio attributes:
                if (realOptions.autoPlay)
                    $(audioElem).attr("autoplay", "autoplay");
                $(audioElem).attr("preload", realOptions.preload);

                $(audioElem).appendTo(thePlayer);
                /*
                // Create error message element
                var errorElem = document.createElement("p");
                $(errorElem).attr("id", "errorMsg");
                $(errorElem).html(realOptions.errorMsg);
                $(errorElem).appendTo(thePlayer);
                */
                // Create the control elements:
                var controlsDivElem = document.createElement("div");
                $(controlsDivElem).addClass("musicPlayer-controls");
                $(controlsDivElem).appendTo(thePlayer);
                var iconsUlElem = document.createElement("ul");
                $(iconsUlElem).appendTo(controlsDivElem);

                // Play/pause button:
                var playLiElem = document.createElement("li");
                $(playLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(playLiElem).attr("title", "Play");
                $(playLiElem).appendTo(iconsUlElem);
                var playSpanElem = document.createElement("span");
                $(playSpanElem).attr("id", "play");
                $(playSpanElem).addClass("ui-icon ui-icon-play");
                $(playSpanElem).appendTo(playLiElem);

                // Previous button:
                var prevLiElem = document.createElement("li");
                $(prevLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(prevLiElem).attr("title", "Previous song");
                $(prevLiElem).appendTo(iconsUlElem);
                var prevSpanElem = document.createElement("span");
                $(prevSpanElem).attr("id", "previous");
                $(prevSpanElem).addClass("ui-icon ui-icon-seek-prev");
                $(prevSpanElem).appendTo(prevLiElem);

                // Next button:
                var nextLiElem = document.createElement("li");
                $(nextLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(nextLiElem).attr("title", "Next song");
                $(nextLiElem).appendTo(iconsUlElem);
                var nextSpanElem = document.createElement("span");
                $(nextSpanElem).attr("id", "next");
                $(nextSpanElem).addClass("ui-icon ui-icon-seek-next");
                $(nextSpanElem).appendTo(nextLiElem);

                // Stop button:
                var stopLiElem = document.createElement("li");
                $(stopLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(stopLiElem).attr("title", "Stop");
                $(stopLiElem).appendTo(iconsUlElem);
                var stopSpanElem = document.createElement("span");
                $(stopSpanElem).attr("id", "stop");
                $(stopSpanElem).addClass("ui-icon ui-icon-stop");
                $(stopSpanElem).appendTo(stopLiElem);

                // Repeat button:
                var repeatLiElem = document.createElement("li");
                $(repeatLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(repeatLiElem).attr("title", "Repeat song");
                $(repeatLiElem).appendTo(iconsUlElem);
                var repeatSpanElem = document.createElement("span");
                $(repeatSpanElem).attr("id", "repeat");
                $(repeatSpanElem).addClass("ui-icon ui-icon-refresh");
                $(repeatSpanElem).appendTo(repeatLiElem);

                // Volume control:
                var muteLiElem = document.createElement("li");
                $(muteLiElem).addClass("musicPlayer-icons ui-state-default ui-corner-all");
                $(muteLiElem).attr("id", "volCtr");
                $(muteLiElem).attr("title", "Mute");
                $(muteLiElem).appendTo(iconsUlElem);
                var muteSpanElem = document.createElement("span");
                $(muteSpanElem).attr("id", "mute");
                $(muteSpanElem).addClass("ui-icon ui-icon-volume-on");
                $(muteSpanElem).appendTo(muteLiElem);

                var volSlideElem = document.createElement("div");
                $(volSlideElem).appendTo(muteLiElem);
                $(volSlideElem).hide();
                var volumeElem = document.createElement("range");
                $(volumeElem).appendTo(volSlideElem);
                $(volumeElem).attr("id", "volumeSlider");

                $("#volumeSlider").slider({
                    orientation: "vertical",
                    range: "min",
                    value: audioElem.volume,
                    min: 0,
                    max: 1,
                    step: 0.05,
                    slide: function (event, ui) {
                        if (ui.value != 0) { muteVolume("unmute"); }
                        else { muteVolume("mute"); }
                        audioElem.volume = ui.value;
                    }
                });

                // Progress bar:
                var progressLiElem = document.createElement("li");
                $(progressLiElem).attr("title", "Progress");
                $(progressLiElem).attr("id", "progress-wrapper");
                $(progressLiElem).appendTo(iconsUlElem);
                var progressBarElem = document.createElement("span");
                $(progressBarElem).attr("id", "progress-bar");
                $(progressBarElem).appendTo(progressLiElem);

                var handleElem = document.createElement("span");
                $(handleElem).attr("id", "handle");
                $(handleElem).addClass("ui-slider-handle");
                $(handleElem).appendTo(progressBarElem);

                // Time left:
                var timeLeftLiElem = document.createElement("li");
                $(timeLeftLiElem).attr("title", "Time left");
                $(timeLeftLiElem).appendTo(iconsUlElem);
                var timeLeftElem = document.createElement("span");
                $(timeLeftElem).attr("id", "timeleft");
                $(timeLeftElem).appendTo(timeLeftLiElem);
                $("#timeleft").text('-0:00');

                // Create playlist wrapper:
                var playlistElem = document.createElement("div");
                $(playlistElem).addClass("musicPlayer-playlist");
                $(playlistElem).appendTo(thePlayer);

                //Show Playlist
                var showListElem = document.createElement("div");
                $(showListElem).attr("id", "showList");
                $(showListElem).attr("title", "Show Playlist");
                $(showListElem).appendTo(playlistElem);
                var showListIconElem = document.createElement("a");
                $(showListIconElem).attr("id", "showListIcon");
                $(showListIconElem).addClass("ui-icon ui-icon-triangle-1-s");
                $(showListIconElem).appendTo(showListElem);

                // Create playlist
                var playlistUlElem = document.createElement("ul");
                $(playlistUlElem).addClass("musicPlayer-playlist-ul");
                $(playlistUlElem).appendTo(playlistElem);
                if (!playlistShow) {
                    $(playlistUlElem).hide();
                }

                // Loop through playlist and add song names to the playlist element
                for (var i = 0; i < playlist.length; i++) {
                    var playlistLiElem = document.createElement("li");
                    $(playlistLiElem).addClass("musicPlayer-playlist-li");
                    $(playlistLiElem).html((i + 1) + ". " + playlist[i][1]);
                    $(playlistLiElem).attr("id", i + "-song");
                    $(playlistLiElem).appendTo(playlistUlElem);
                }
                $("#" + currentSong + "-song").addClass("nowPlaying");

                /**** Event handlers: ****/
                if(playlist.length > 0)
                {
                    $("#hidden").val(playlist[0][2]).trigger('change');
                }
                // Play/pause:
                $(audioElem).bind('play', function () {
                    $("#play").addClass("ui-icon ui-icon-pause");
                    $("#play").attr("title", "Pause");
                    $("#" + currentSong + "-song").addClass("nowPlaying");
                    $(audioElem).attr("autoplay", "autoplay");
                }).bind('pause ended', function () {
                    $("#play").removeClass("ui-icon ui-icon-pause");
                    $("#play").addClass("ui-icon ui-icon-play");
                    $("#play").attr("title", "Play");
                    $(audioElem).removeAttr("autoplay");
                });

                // End of song reached:
                $(audioElem).bind("ended", function () {
                    $("#" + currentSong + "-song").removeClass("nowPlaying");
                    // Check if we are at the end of the playlist:
                    if (currentSong == playlist.length - 1)
                        currentSong = 0;
                    else
                        currentSong++;
                    $("#audioPlayer").attr("src", playlist[currentSong][0]);
                    $("#hidden").val(playlist[currentSong][2]).trigger('change');
                    $("#" + currentSong + "-song").addClass("nowPlaying");
                    $(".musicPlayer-currentSongTicker").html(playlist[currentSong][1]);
                    audioElem.play();
                });

                // Update progress:
                $(audioElem).bind('timeupdate', function () {
                    var rem = parseInt(audioElem.duration - audioElem.currentTime, 10);
                    var pos = (audioElem.currentTime / audioElem.duration) * 100;
                    var mins = Math.floor(rem / 60, 10);
                    var secs = rem - mins * 60;

                    $("#timeleft").text('-' + mins + ':' + (secs > 9 ? secs : '0' + secs));

                    $("#progress-bar").slider({
                        value: 0,
                        step: 0.01,
                        orientation: "horizontal",
                        handle: "#handle",
                        range: "min",
                        min: 0,
                        max: audioElem.duration,
                        //animate: true,
                        slide: function () {
                            manualSeek = true;
                        },
                        stop: function (e, ui) {
                            manualSeek = false;
                            audioElem.currentTime = ui.value;
                        }
                    });
                    $("#handle").css({ left: pos + '%' });
                });

                // On error:
                $(audioElem).bind('error', function () {
                    $(".musicPlayer-currentSongTicker").html("Error: Could not play song: " + playlist[currentSong][1]);
                    $(".musicPlayer-currentSongTicker").addClass("ui-state-error");
                });
                $(audioElem).bind('canplay', function () {
                    $(".musicPlayer-currentSongTicker").removeClass("ui-state-error");
                });

                /**** Click events ****/

                $("#play").click(function () {
                    if (audioElem.paused)
                        audioElem.play();
                    else
                        audioElem.pause();
                });

                $("#previous").click(function () {
                    $("#" + currentSong + "-song").removeClass("nowPlaying");
                    // Check if we are at the start of the playlist:
                    if (currentSong == 0)
                        currentSong = playlist.length - 1;
                    else
                        currentSong--;
                    $("#" + currentSong + "-song").addClass("nowPlaying");
                    $("#audioPlayer").attr("src", playlist[currentSong][0]);
                    $("#hidden").val(playlist[currentSong][2]).trigger('change');
                    $(".musicPlayer-currentSongTicker").html(playlist[currentSong][1]);
                    $("#timeleft").text('-0:00');
                });

                $("#next").click(function () {
                    $("#" + currentSong + "-song").removeClass("nowPlaying");
                    // Check if we are at the end of the playlist:
                    if (currentSong == playlist.length - 1)
                        currentSong = 0;
                    else
                        currentSong++;
                    $("#" + currentSong + "-song").addClass("nowPlaying");
                    $("#audioPlayer").attr("src", playlist[currentSong][0]);
                    $("#hidden").val(playlist[currentSong][2]).trigger('change');
                    $(".musicPlayer-currentSongTicker").html(playlist[currentSong][1]);
                    $("#timeleft").text('-0:00');
                });


                $("#stop").click(function () {
                    audioElem.pause();
                    if (audioElem.loaded)
                        audioElem.currentTime = 0;
                });

                $("#repeat").click(function () {
                    if (repeatOne) {
                        $("#audioPlayer").removeAttr("loop");
                        repeatOne = false;
                        $(this).removeClass("ui-icon ui-icon-arrow-1-e");
                        $(this).addClass("ui-icon ui-icon-refresh");
                        $(repeatLiElem).attr("title", "Repeat song");
                    }
                    else {
                        $("#audioPlayer").attr("loop", "loop");
                        repeatOne = true;
                        $(this).removeClass("ui-icon ui-icon-refresh");
                        $(this).addClass("ui-icon ui-icon-arrow-1-e");
                        $(repeatLiElem).attr("title", "No repeat");
                    }
                });

                // Song selected from playlist:
                $(".musicPlayer-playlist-li").click(function (e) {
                    audioElem.pause();
                    $("#" + currentSong + "-song").removeClass("nowPlaying");
                    currentSong = $(this).attr('id')[0];
                    $("#audioPlayer").attr("src", playlist[currentSong][0]);
                    $("#hidden").val(playlist[currentSong][2]).trigger('change'); ;
                    $(".musicPlayer-currentSongTicker").html(playlist[currentSong][1]);
                    audioElem.play();
                });

                // Volume control:
                function muteVolume(state) {
                    if (state != "mute") {
                        audioElem.muted = false;
                        audioElem.volume = 0.8;
                        $("#volumeSlider").slider({ value: 0.8 });
                        $("#mute").removeClass("ui-icon ui-icon-volume-off");
                        $("#mute").addClass("ui-icon ui-icon-volume-on");
                        $("#mute").attr("title", "Mute");
                    }
                    else {
                        audioElem.muted = true;
                        audioElem.volume = 0;
                        $("#volumeSlider").slider({ value: 0 });
                        $("#mute").removeClass("ui-icon ui-icon-volume-on");
                        $("#mute").addClass("ui-icon ui-icon-volume-off");
                        $("#mute").attr("title", "Turn volume on");
                    }
                }

                $("#mute").hover(function () { $(volSlideElem).show(); });
                $("#volCtr").mouseleave(function () { $(volSlideElem).hide(); });

                $("#mute").click(function () {
                    if (audioElem.muted)
                        muteVolume("unmute");
                    else
                        muteVolume("mute");
                });

                // Playlist:
                $("#showList").click(function () {
                    if (!playlistShow) {
                        $(playlistUlElem).show();
                        playlistShow = true;
                        $("#showListIcon").removeClass("ui-icon ui-icon-triangle-1-s");
                        $("#showListIcon").addClass("ui-icon ui-icon-triangle-1-n");
                        $("#showList").attr("title", "Hide playlist");
                    }
                    else {
                        $(playlistUlElem).hide();
                        playlistShow = false;
                        $("#showListIcon").removeClass("ui-icon ui-icon-triangle-1-n");
                        $("#showListIcon").addClass("ui-icon ui-icon-triangle-1-s");
                        $("#showList").attr("title", "Show playlist");
                    }
                });


            }

            /*********************************************************************************************************************************************************************/
            // No support for HTML5 audio or mp3 files, fallback to Nifty flash player
            else {
                var audioElem = document.createElement("div");
                $(audioElem).attr("id", "audioPlayer");
                $(audioElem).appendTo(thePlayer);

                // Create playlist element:
                var playlistElem = document.createElement("div");
                $(playlistElem).addClass("musicPlayer-playlist");
                $(playlistElem).appendTo(thePlayer);

                // Create playlist:
                var playlistUlElem = document.createElement("ul");
                $(playlistUlElem).addClass("musicPlayer-playlist-ul");
                $(playlistUlElem).appendTo(playlistElem);

                // Loop through playlist and add song names to the playlist element:
                for (var i = 0; i < playlist.length; i++) {
                    // Add song to playlist:
                    var playlistLiElem = document.createElement("li");
                    $(playlistLiElem).addClass("musicPlayer-playlist-li");
                    $(playlistLiElem).html((i + 1) + ". " + playlist[i][1]);
                    $(playlistLiElem).attr("id", i + "-song");
                    $(playlistLiElem).appendTo(playlistUlElem);
                }

                // Message to user:
                var niftyMsg = document.createElement("p");
                $(niftyMsg).html("*Using Niftyplayer due to browser limitations. Niftyplayer does not support external mp3 files."
                               + " We recommend Google Chrome for optimal performance.");
                $(niftyMsg).attr("id", "niftyMsg");
                $(niftyMsg).appendTo(thePlayer);

                // Create player:
                $(".musicPlayer-playlist-li").click(function (e) {
                    $("#" + currentSong + "-song").removeClass("nowPlaying");
                    currentSong = $(this).attr('id')[0];
                    $("#" + currentSong + "-song").addClass("nowPlaying");

                    $(".musicPlayer-currentSongTicker").html(playlist[currentSong][1]);
                    var songSrc = String(playlist[currentSong][0] + '&as=1"');
                    var obj = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
                              'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ' +
                              'width="165" height="38" id="niftyPlayer1" align=""><param name=movie value="niftyplayer/niftyplayer.swf?file=';
                    obj += songSrc;
                    obj += '>  <param name=quality value=high> <param name=bgcolor value=#404040>  <embed src="niftyplayer/niftyplayer.swf?file='
                    obj += songSrc;
                    obj += 'quality=high bgcolor=#404040 width="165" height="38" name="niftyPlayer1" align="" type="application/x-shockwave-flash"' +
                           'pluginspage="http://www.macromedia.com/go/getflashplayer"> </embed></object>'
                    $(audioElem).html(obj);
                });
            }
        });
    }
})(jQuery); 